<script setup>
import {onMounted, ref} from 'vue'
import axios from "axios";
import QAVue from "./QAVue.vue";

const question = ref('')

const answer = ref('')

function ask() {
    // 获取 和 后端的连接
    const eventSource = new EventSource('/api/chat/stream2/' + question.value)
    let sse;
    console.log(eventSource.target)


    // 类比这个
    let el = document.querySelector("div")
    el.onclick = () => { // 触发时机 是 当 el 元素被点击时触发相应 的函数

    }

    eventSource.onopen = (event) => {
        console.log("open")
        sse = event.target

    }

    eventSource.onmessage = (event) => {
        // 结束的标志 跟后端最后发送的一条内容有关
        if (event.data === 'DONE') {
            sse.close()
            console.log("关闭")
            return
        }
        answer.value += event.data
    }

    eventSource.onerror = (error) => {
        console.log(error)
    }
    eventSource.onclose = () => {
        console.log("open")
    }
}
const msgList = ref([])
function getHistory () {
    axios.get('/api/chat/getHistory').then(res => {
        console.log(res)
        msgList.value = res.data
    })
}

onMounted(() => {
    getHistory()
})
</script>

<template>
    <QAVue :answer="message.answer" :question="message.question" v-for="message in msgList" />
    <input v-model="question"/>
    <button @click="ask">提问</button>
    <textarea v-model="answer" />
</template>

<style scoped>
</style>
